package com.dfhc.sample.member.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.quickbundle.base.web.page.RmPageVo;
import org.quickbundle.project.RmProjectHelper;
import org.quickbundle.tools.helper.RmJspHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.dfhc.ISystemConstant;
import com.dfhc.PjException;
import com.dfhc.pub.concurrencycontrol.RequestConcurrentRoute;
import com.dfhc.pub.service.ExcelService;
import com.dfhc.pub.service.PubParamService;
import com.dfhc.rm.user.IUserConstants;
import com.dfhc.rm.user.service.UserService;
import com.dfhc.rm.user.vo.UserVo;
import com.dfhc.util.CsrfHelper;
import com.dfhc.util.FileOperateHelper;
import com.dfhc.util.JspHelper;
import com.dfhc.util.StringHelper;
import com.dfhc.wk.nodeproperty.vo.NodePropertyVo;

/**
 * @author ASUS
 * 会员列表(例子)
 */
@Controller
@RequestMapping(value = "/sample/member")
public class MemberController implements IUserConstants {
	@Autowired
	private UserService userService;
	@Autowired
	private PubParamService pubParamService;
	/**
     * 简单查询，分页显示，支持表单回写
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "")
    public String list(Model model, HttpServletRequest request) {
    	model.addAttribute(ISystemConstant.QUERY_STRING, request.getQueryString());//全部参数
    	Map<String, Object> searchPara = getQueryCondition(request);  //从request中获得查询条件
        RmPageVo pageVo = RmJspHelper.transctPageVo(request, userService.getCount(searchPara));
        String orderStr = RmJspHelper.getOrderStr(request);  //得到排序信息
        List<UserVo> beans = userService.list(searchPara, orderStr, pageVo.getStartIndex(), pageVo.getPageSize());  //按条件查询全部,带排序
        RmJspHelper.saveOrderStr(orderStr, request);  //保存排序信息
        model.addAttribute(REQUEST_QUERY_CONDITION, searchPara);
        model.addAttribute(REQUEST_BEANS, beans);  //把结果集放入request
        return "/sample/member/member-list";
    }
    /**
     * 跳转到新增页面
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "addPage")
    public String addPage(Model model, HttpServletRequest request) {    	            
        return "/sample/member/member-add";
    }
 
    /**
     * 跳转到编辑和查看页面
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "showPage")
    public String showPage(Model model, HttpServletRequest request) {
    	//获取id
    	String id = request.getParameter(IUserConstants.REQUEST_ID);
    	//根据id查询用户
    	if(!StringHelper.isEmpty(id)){
    		UserVo userVo = userService.get(id);
    		model.addAttribute(REQUEST_BEAN, userVo);
    	}
        return "/sample/member/member-add";
    }
    /**
     * 从request中获得查询条件
     * @param request http请求对象
     * @return 条件Map
     */
    public static Map<String, Object> getQueryCondition(HttpServletRequest request) {
        Map<String, Object> searchMap = null;
        if(request.getAttribute(REQUEST_QUERY_CONDITION) != null) {  //如果request.getAttribute中有，就不取request.getParameter
            searchMap = (Map<String, Object>)request.getAttribute(REQUEST_QUERY_CONDITION);
        } else {
           searchMap = new HashMap<String, Object>();
           searchMap.put("id", request.getParameter("id"));
           searchMap.put("name", request.getParameter("name"));
           searchMap.put("lockStatus", request.getParameter("lockStatus"));
           searchMap.put("loginId", request.getParameter("loginId"));
           searchMap.put("password", request.getParameter("password"));
           searchMap.put("authenType", request.getParameter("authenType"));
           searchMap.put("organizationId", request.getParameter("organizationId"));
           searchMap.put("employeeId", request.getParameter("employeeId"));
           searchMap.put("email", request.getParameter("email"));
           searchMap.put("adminType", request.getParameter("adminType"));
           searchMap.put("description", request.getParameter("description"));
           searchMap.put("agentStatus", request.getParameter("agentStatus"));
           searchMap.put("loginStatus", request.getParameter("loginStatus"));
           searchMap.put("lastLoginDate", request.getParameter("lastLoginDate"));
           searchMap.put("lastLoginIp", request.getParameter("lastLoginIp"));
           searchMap.put("loginSum", request.getParameter("loginSum"));
           searchMap.put("lastCustomCss", request.getParameter("lastCustomCss"));
           searchMap.put("isAffix", request.getParameter("isAffix"));
           searchMap.put("functionPermission", request.getParameter("functionPermission"));
           searchMap.put("dataPermission", request.getParameter("dataPermission"));
           searchMap.put("custom1", request.getParameter("custom1"));
           searchMap.put("custom2", request.getParameter("custom2"));
           searchMap.put("custom3", request.getParameter("custom3"));
           searchMap.put("custom4", request.getParameter("custom4"));
           searchMap.put("custom5", request.getParameter("custom5"));
           searchMap.put("customXml", request.getParameter("customXml"));
           searchMap.put("usableStatus", ISystemConstant.DICTIONARY_RM_YES_NOT_1);
           searchMap.put("modifyDate", request.getParameter("modifyDate"));
           searchMap.put("modifyIp", request.getParameter("modifyIp"));
           searchMap.put("modifyUserId", request.getParameter("modifyUserId"));
           searchMap.put("createTime", request.getParameter("createTime"));
           searchMap.put("createUserName", request.getParameter("createUserName"));
           searchMap.put("attribute1", request.getParameter("attribute1"));
           searchMap.put("attribute2", request.getParameter("attribute2"));
           searchMap.put("attribute3", request.getParameter("attribute3"));
           searchMap.put("attribute4", request.getParameter("attribute4"));
           searchMap.put("attribute5", request.getParameter("attribute5"));
           searchMap.put("delete_flag",ISystemConstant.DICTIONARY_RM_YES_NOT_0);
           searchMap.put("searchName", request.getParameter(ISystemConstant.SEARCH_NAME));
        }
        return searchMap;
    }
    /**
     * ajax 请求列表数据
     * @param model
     * @param request
     * @return
     * @throws IOException 
     */
    @RequestMapping(value = "ajaxList",  produces="application/json")
    @ResponseBody
    public  Map<String,Object> ajaxList(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException{
          boolean bLock = false;
          Map map = new HashMap();  
          Enumeration paramNames = request.getParameterNames();  
          while (paramNames.hasMoreElements()) {  
              String paramName = (String) paramNames.nextElement();  

              String[] paramValues = request.getParameterValues(paramName);  
              if (paramValues.length == 1) {  
                  String paramValue = paramValues[0];  
                   if (paramValue.length() != 0) {  
                       map.put(paramName, paramValue);  
                   }  
               }  
           }  

           Set<Map.Entry<String, String>> set = map.entrySet();  
           Map<String,Object> dataMap=new HashMap<String,Object>();
           try{
	    	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));
            //获取开始记录数
	        String startRow = request.getParameter(ISystemConstant.PAGE_START_KEY);
	        String rows=request.getParameter(ISystemConstant.PAGE_SIZE_KEY)==null?ISystemConstant.DEFAULT_PAGE_SIZE:request.getParameter(ISystemConstant.PAGE_SIZE_KEY);	        
	        int rowsInt=Integer.parseInt(rows);//页大小
	        if(StringHelper.isEmpty(startRow)){
	        	startRow="0";
	        }
	        int startRowInt = Integer.parseInt(startRow);
	        Map<String, Object> searchPara = getQueryCondition(request);  //从request中获得查询条件
	        int totalNum = userService.getCount(searchPara);
	        String orderStr = JspHelper.getOrderStr(request);  //得到排序信息
        
        	List<UserVo> beans = userService.list(searchPara, orderStr, startRowInt+1, rowsInt);  //按条件查询全部,带排序
        	//翻译状态码
        	if(beans!=null){
	        	for(UserVo bean:beans){
				//如果状态码字段有其他用途，请用扩展字段attribute1-attribute5代替
	        		if(ISystemConstant.DICTIONARY_RM_YES_NOT_1.equals(bean.getLoginStatus())){
	        			bean.setLoginStatus("已登录");
	        		}else{
	        			bean.setLoginStatus("未登录");
	        		}
	        		if(bean.getAuthenType()==null){
	        			bean.setAuthenType("");
	        		}
	        	}
        	}      
        	dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
	        dataMap.put(ISystemConstant.PAGE_DRAW, request.getParameter(ISystemConstant.PAGE_DRAW));
	        //"recordsTotal"
        	dataMap.put(ISystemConstant.RECORDS_TOTAL,totalNum);
	        dataMap.put(ISystemConstant.RECORDS_FILTERED, totalNum);
        	dataMap.put(ISystemConstant.DATA, beans);
        	return dataMap;
          }catch(Exception e){
        	  e.printStackTrace();
        	  RmProjectHelper.logInf(StringHelper.exceptionToString(e));
        	  dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
        	  dataMap.put(ISystemConstant.AJAX_MESSAGE, "查询失败!");
        	  return dataMap;
          }finally{
	        //最后解锁
	        RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID),bLock);	        
          }
    }
    /**
     * 从页面表单获取信息注入vo，并插入单条记录
     * @param request http请求对象
     * @param vo 值对象
     * @return 返回Ajax应答实体对象
     */
    @RequestMapping(value = "insert", method = RequestMethod.POST, 
			consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String,Object> insert(HttpServletRequest request, @Valid UserVo vo) {
          boolean bLock = false;
          try{
        	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));        	
	        Map<String, Object> result = new HashMap<String, Object>();
	        try{
		        userService.insert(request,vo);
	        	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
		        result.put(ISystemConstant.AJAX_MESSAGE, "新增用户成功!" );
	        }catch(Exception e){
	        	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
		        result.put(ISystemConstant.AJAX_MESSAGE, "新增用户失败!");	        	
	        }
	        return result;
          }finally{
    		//最后解锁
    		RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID),bLock);
          }
    }
    /**
     * 从页面表单获取信息注入vo，并更新单条记录
     * @param request http请求对象
     * @param vo 值对象
     * @return 返回Ajax应答实体对象
     */
    @RequestMapping(value = "update", method = RequestMethod.POST, 
			consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String,Object> update(HttpServletRequest request, @Valid UserVo vo) {
          boolean bLock = false;
          try{
        	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));        	
	        Map<String, Object> result = new HashMap<String, Object>();
	        try{
		        userService.update(request,vo);
	        	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
		        result.put(ISystemConstant.AJAX_MESSAGE, "更新用户成功!" );
	        }catch(Exception e){
	        	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
		        result.put(ISystemConstant.AJAX_MESSAGE, "更新用户失败!");	        	
	        }
	        return result;
          }finally{
    		//最后解锁
    		RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID),bLock);
          }
    }
    /**
     * 删除单条记录
     * @param request http请求对象
     * @return 返回Ajax应答实体对象
     */
    @RequestMapping(value = "delete", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String,Object> delete(HttpServletRequest request) {
          boolean bLock = false;
          try{
        	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));        	
	        Map<String, Object> result = new HashMap<String, Object>();
	        try{
		        userService.delete(request.getParameter(REQUEST_ID));
	        	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
		        result.put(ISystemConstant.AJAX_MESSAGE, "删除用户成功!" );
	        }catch(Exception e){
	        	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
		        result.put(ISystemConstant.AJAX_MESSAGE, "删除用户失败!");	        	
	        }
	        return result;
          }finally{
    		//最后解锁
    		RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID),bLock);
          }
    }
    /**
     * 导出通用业务表数据为xls,并下载
     * @throws Exception 
     *
     */
     @RequestMapping(value="exportXls"+ISystemConstant.SUFFIX_ACTION)
     public void frontExportXls(Model model,HttpServletRequest request,HttpServletResponse response) throws Exception{	
           exportXls(model, request, response);
     }
    /**
     * 导出通用业务表数据为xls,并下载
     * @throws Exception 
     **/
    @RequestMapping(value="exportXls")
    public void backExportXls(Model model,HttpServletRequest request,HttpServletResponse response) throws Exception{	
           exportXls(model, request, response);
    }
    /**
     * 导出xls公共方法
     * @param model
     * @param request
     * @param response
     * @throws UnsupportedEncodingException
     */
    private void exportXls(Model model, HttpServletRequest request,
 		HttpServletResponse response) throws UnsupportedEncodingException {
           boolean bLock = false;
           try{
 	    	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));

 	    	//获取排序
 	    	String order = request.getParameter(ISystemConstant.PREDEFINED_ORDER);
 	    	if(!StringHelper.isEmpty(order)){
 			String order1 = new String(order.getBytes("ISO-8859-1"),"UTF-8");
 		    	order = java.net.URLDecoder.decode(order1, "UTF-8");
 	    	}
 	    	Map<String, Object> searchPara = new HashMap<String,Object>();
 	    	searchPara.put("delete_flag",ISystemConstant.DICTIONARY_RM_YES_NOT_0);
 	    	List<UserVo> vos = userService.list(searchPara, order);    		
 	    	String sheetName = request.getParameter(ISystemConstant.PREDEFINED_SHELL_NAME);
 	    	if(StringHelper.isEmpty(sheetName)){
 	    		sheetName = ISystemConstant.DEFAULT_SHELL_NAME;
 	    	}
 	    	LinkedHashMap<String,String> fieldMap = new LinkedHashMap<String,String>();
 	    	//获取删除的列名
 	    	String deletes = request.getParameter(ISystemConstant.PREDEFINED_EXPORT_DELETE_COLUMNNAMES);
 	    	List<String> deleteList =  new ArrayList<String>();
 	    	if(!StringHelper.isEmpty(deletes)){
 	    		deleteList = Arrays.asList(deletes.split(","));
 	    	}
 	    	//所有字段放入fieldMap
 	    	fieldMap.put("id","ID");
 	    	fieldMap.put("name","用户名");
 	    	fieldMap.put("loginId","登录账号");
 	    	fieldMap.put("authenType","授权类型");
 	    	fieldMap.put("email","邮箱");
 	    	fieldMap.put("adminType","管理类型");
 	    	fieldMap.put("loginStatus","登录状态");
 	    	fieldMap.put("createTime","注册日期");
 	    	//删除无用字段
 	    	for(String  propertyName:deleteList){
 	    	    if(fieldMap.containsKey(propertyName)){
 	    		fieldMap.remove(propertyName);
 	    		continue;
 	    	    }
 	    	}
 	    	
 	    	//获取需要隐藏的列数组
 	    	String hides = request.getParameter(ISystemConstant.PREDEFINED_EXPORT_HIDE_COLUMNNAMES);
 	    	
 	    	List<String> hideList =  new ArrayList<String>();
 	    	if(!StringHelper.isEmpty(hides)){
 	    		hideList = Arrays.asList(hides.split(","));
 	    	}
 	    	ExcelService.listToExcel(vos, fieldMap, hideList,sheetName, response);		
           }finally{
 	    	//最后解锁
 	    	RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID),bLock);
           }
     }    
    /**
     * 前台导入通用业务表数据为xls到数据库
     * @throws Exception
     **/
    @RequestMapping(value="importXls"+ISystemConstant.SUFFIX_ACTION)
    public void frontImportXls(HttpServletRequest request, HttpServletResponse response) throws Exception{
    	importXls(request, response);
    }
    /**
     * 后台导入通用业务表数据为xls到数据库
     * @throws Exception
     **/
    @RequestMapping(value="importXls")
    public void backImportXls(HttpServletRequest request, HttpServletResponse response) throws Exception{
    	importXls(request, response);
    }
    /**
     * 导入xls公共方法
     * @param request
     * @param response
     */
    private void importXls(HttpServletRequest request, HttpServletResponse response) throws Exception {
          boolean bLock = false;
          try{
	    	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));

		   try {
			//获取上传文件xls
			List<MultipartFile> uploadFiles = FileOperateHelper.listMultipartFile(request);
			if(uploadFiles==null ||uploadFiles.isEmpty()){
				throw new PjException("缺少上传文件!");
			}
			String sheetName = request.getParameter(ISystemConstant.PREDEFINED_SHELL_NAME);
			if(StringHelper.isEmpty(sheetName)){
		    		sheetName = ISystemConstant.DEFAULT_SHELL_NAME;
			}
			LinkedHashMap<String,String> fieldMap = new LinkedHashMap<String,String>();
			String idCnName=null;//id中文名

			idCnName ="登录账号";
//			fieldMap.put("ID","id");

			fieldMap.put("用户名","name");
 	    	fieldMap.put("登录账号","loginId");
 	    	fieldMap.put("授权类型","authenType");
 	    	fieldMap.put("邮箱","email");
 	    	fieldMap.put("管理类型","adminType");
 	    	fieldMap.put("登录状态","loginStatus");
 	    	fieldMap.put("注册日期","createTime");


			MultipartFile mfile = uploadFiles.get(0);

			List<UserVo> vos =null;
			InputStream inputStream = null;
			try{
				inputStream = mfile.getInputStream();
				if(!StringHelper.isEmpty(idCnName)){
					vos = ExcelService.excelToList(inputStream, sheetName, UserVo.class, fieldMap, new String[]{idCnName});
				}else{
					vos = ExcelService.excelToList(inputStream, sheetName, UserVo.class, fieldMap, new String[]{});
				}
			}finally{
				if(inputStream!=null){
					inputStream.close();
					inputStream = null;
				}
			}

//			userService.insertBatch(vos);
			//填写默认值
			if(vos!=null &&vos.size()>0){
				for(UserVo userVo:vos){
					if(StringHelper.isEmpty(userVo.getLockStatus())){
						//默认激活
						userVo.setLockStatus(ISystemConstant.DICTIONARY_RM_YES_NOT_1);
					}
					//默认为可用
					if(StringHelper.isEmpty(userVo.getUsableStatus())){
						userVo.setUsableStatus(ISystemConstant.DICTIONARY_RM_YES_NOT_1);
					}
					if(StringHelper.isEmpty(userVo.getUsable_status())){
						userVo.setUsable_status(ISystemConstant.DICTIONARY_RM_YES_NOT_1);
					}
				}
				userService.insertUpdateBatch(vos.toArray(new UserVo[vos.size()]));
			}
		   } catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();//
			result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);			
			result.put(ISystemConstant.AJAX_MESSAGE, e.getMessage());
			response.setContentType("text/html;charset=utf-8");
   	                result.put(ISystemConstant.CSRF_CODE, CsrfHelper.getCsrfCode(request));
			try {
				response.getWriter().print(JSONObject.toJSONString(result));
				response.getWriter().flush();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			return;
		   }
		   Map<String, Object> result = new HashMap<String, Object>();
		   result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
		   result.put(ISystemConstant.AJAX_MESSAGE, "导入成功!");
  	           result.put(ISystemConstant.CSRF_CODE, CsrfHelper.getCsrfCode(request));
		   response.setContentType("text/html;charset=utf-8");
		   try {
			response.getWriter().print(JSONObject.toJSONString(result));
			response.getWriter().flush();
		   } catch (IOException e) {
			e.printStackTrace();
		   }
          }finally{
		   //最后解锁
		   RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID),bLock);
          }
    }

}
